package com.linfeng.api.util.hdk;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import com.linfeng.api.util.HttpRequestMethod;
import com.linfeng.common.constant.ShopConstants;
import com.linfeng.common.exception.TrymallException;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 访问好单库api的执行方法
 * @author linfeng
 * @date 2021/1/19 19:31
 */
public class HdkApiRequest {

    public static String doRequest(Object object) throws Exception {

        String requestMethod =ReflectUtil.invoke(object,"getRequestMethod");
        //请求体拼接
        Field[] fields = ReflectUtil.getFields(object.getClass());
        Object[] fieldsValue = ReflectUtil.getFieldsValue(object);
        String requestBody = "";
        Map<String,Object> requestBodyMap = new HashMap<>();

        for (int i = 0;i < fields.length;i++) {
            Field field = fields[i];
            Object fieldValue = fieldsValue[i];
            if (fieldValue != null) {
                if (HttpRequestMethod.GET.equals(requestMethod)) {
                    requestBody+= "/"+ field.getName() + "/" + fieldValue;
                } else if (HttpRequestMethod.POST.equals(requestMethod)) {
                    requestBodyMap.put(field.getName(),fieldValue);
                }
            }
        }

        String apiUrl = ReflectUtil.invoke(object,"getApiUrl");
        HttpResponse httpResponse = null;
        //发送api请求
        if (HttpRequestMethod.GET.equals(requestMethod)) {
            httpResponse = HttpRequest.get(apiUrl + requestBody).execute();
        } else if (HttpRequestMethod.POST.equals(requestMethod)) {
            httpResponse = HttpRequest.post(apiUrl).form(requestBodyMap).execute();
        }
        //处理响应体
        if (httpResponse.getStatus() != HttpStatus.HTTP_OK) {
            throw new TrymallException("好单库API请求失败：" + httpResponse.getStatus());
        }
            String body = httpResponse.body();
            JSONObject jsonObject = new JSONObject(body);
            Object code = jsonObject.get("code");
            String msg = (String) jsonObject.get("msg");

            if (code instanceof Integer) {
                int codeInt = ((Integer) code).intValue();
                if (codeInt != 1) {
                    throw new TrymallException(msg);
                }
            }
            
            if (code instanceof String) {
                String codeString = code.toString();
                if (!ShopConstants.ONE.equals(codeString)) {
                    throw new TrymallException(msg);
                }
            }

            return body;

    }

}
